package com.augurit.gis.edit;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.esri.arcgis.carto.*;
import com.esri.arcgis.display.IMovePointFeedbackProxy;
import com.esri.arcgis.geodatabase.*;
import com.esri.arcgis.geometry.*;
import com.esri.arcgis.geoprocessing.tools.coveragetools.Transform;
import com.esri.arcgis.server.IServerContext;
import com.esri.arcgis.interop.AutomationException;

import com.augurit.gis.server.ServerContextFactory;

@Service
public class EditService {	
	private Map<String, String> serviceMap;// 业务名称对应arcgis server服务名称
	
	
	/**
	 * 根据业务名称获得服务名称
	 * @param ywName 业务名称
	 * @return 服务名称
	 */
	public String getServiceName(String ywName)
	{
		if(serviceMap==null)
			initstatusMap();
		return serviceMap.get(ywName);
	}
	
	private void initstatusMap() {
		// 初始化数据部分对应的map
		serviceMap = new HashMap<String, String>();
		serviceMap.put("rqssgd", "gzcgwywrqssgd");
		serviceMap.put("rqrsqjazwxqyzz", "gzcgwywrqqyzz");
		serviceMap.put("hwggshsqb", "gzcgwywhwgg");
		serviceMap.put("rqjyxkz_gdqy", "gzcgwywrqjyxkgdrq");
		serviceMap.put("rqjyxkz_pzqy", "gzcgwywrqjyxkyhq");
		serviceMap.put("csdlwj", "gzcgwywdlwj");
		serviceMap.put("jzljczz_xzfz", "gzcgwywync");
		serviceMap.put("jzfqwczz", "gzcgwywyncfq");
		serviceMap.put("csdllszysp", "gzcgwywzy");
		serviceMap.put("ccgbggcs", "gzcgwywwc");
		serviceMap.put("shljys", "gzcgwywljys");
		serviceMap.put("shljcz", "gzcgwywljcz");
		serviceMap.put("shljqssj", "gzcgwywljqs");
		serviceMap.put("rqjyxkzqx_gdqy", "gzcgwywrqjyxkgdrq_qu");
		serviceMap.put("rqjyxkzqx_pzqy", "gzcgwywrqjyxkyhq_qu");
	
	}
	@SuppressWarnings({ "unused", "unchecked" })
	public void SayHello()
	{
		System.out.println("I am about to eidt");
		
	}
	//新增点
	@SuppressWarnings({ "unused", "unchecked" })
	 public String addPoint(java.lang.Double x,java.lang.Double y,String serverName,String serverType,Integer layerId,String acceptNo ,String caseType) throws AutomationException,IOException
	 {
	  IServerContext context = null;
      try
      {
    	     context =ServerContextFactory.getContext(serverName, serverType);
			  MapServer mapServer = (MapServer) context.getServerObject();
			  ILayer editLayer = mapServer.getLayer("",layerId);
			  System.out.println("编辑的图层名称:"+editLayer.getName());
			  IFeatureLayer featureLayer = new IFeatureLayerProxy(editLayer);
			  IFeatureClass featureClass = featureLayer.getFeatureClass();
			  IFeature feature = featureClass.createFeature();
			  IFields fields = feature.getFields(); 
			  IPoint point = (IPoint)context.createObject(Point.getClsid());
			  point.setX(x);
			  point.setY(y);
			  feature.setShapeByRef(point);
			  feature.setValue(fields.findField("acceptNo"), acceptNo);
			  //保存为未结案，0:未结案，1:结案
			  feature.setValue(fields.findField("IsClose"),0);
			  feature.setValue(fields.findField("CASETYPE"), caseType);
			  feature.store();  
	    	  context.releaseContext();
	    	  return EditResult.Succeed;
      }
      catch(Exception ee)
      {
    	  ee.printStackTrace();
    	  if(context!=null)
    	  {
    	    context.releaseContext();
    	  }
    	  return EditResult.Failed;
      }
	}
	
	//修改点的坐标
	@SuppressWarnings({ "unused", "unchecked" })
	 public String modifyPoint(java.lang.Double x,java.lang.Double y,String serverName,String serverType,Integer layerId,String acceptNo,String caseType ) throws AutomationException,IOException
	 {
	  IServerContext context = null;
	  IFeatureCursor featureCursor=null;
      try
      {
    	     context =ServerContextFactory.getContext(serverName, serverType);
			  MapServer mapServer = (MapServer) context.getServerObject();
			  ILayer editLayer = mapServer.getLayer("",layerId);
			  IFeatureLayer featureLayer = new IFeatureLayerProxy(editLayer);
			  IFeatureClass featureClass = featureLayer.getFeatureClass();
			  //IQueryFilter queryFilter = new QueryFilter();//不能使用这种方法
			  IQueryFilter queryFilter =(IQueryFilter)context.createObject(QueryFilter.getClsid());
			  String whereString="\"ACCEPTNO\" = '"+acceptNo+"'";
			  System.out.println(whereString);
			  queryFilter.setWhereClause(whereString);  
			  //queryFilter.setSubFields("ACCEPTNO") ;//设置了这个选项以后，将缺少shape
			  featureCursor = featureClass.IFeatureClass_update(queryFilter, false);
			  IFeature feature;
			  if((feature = featureCursor.nextFeature()) != null)
			  {
				  System.out.println("已经找到acceptNo为"+acceptNo+"的案件");
				  IPoint point = (IPoint)context.createObject(Point.getClsid());
				  point.setX(x);
				  point.setY(y); 
				  feature.setShapeByRef(point);
				  feature.store();
				  context.releaseContext();
				  return EditResult.Succeed;
			  }
			  else 
			  {
				  context.releaseContext();
				  System.out.println("找不到acceptNo为"+acceptNo+"的案件");
				  return EditResult.Failed;
			   }
      }
      catch(Exception ee)
      {
    	  ee.printStackTrace();
    	  if(context!=null)
    	  {
    		  
    	      context.releaseContext();
    	  }
    	  return EditResult.Failed;
      }
	}
	
	//修改点的属性
	//fieldAndValue="field1,value1;field2,value2;field3,value3......"
	@SuppressWarnings({ "unused", "unchecked" })
	 public String savePointProperty(String fieldAndValue,String serverName,String serverType,Integer layerId,String acceptNo ) throws AutomationException,IOException
	 {
	  if(serverName==null)
	  {
		  System.out.println("配置数组中缺少相应业务的服务名称，请添加该业务的配置");
		  return EditResult.Failed;
	  }
	  IServerContext context = null;
	  IFeatureCursor featureCursor=null;
      try
      {
    	     context =ServerContextFactory.getContext(serverName, serverType);
			  MapServer mapServer = (MapServer) context.getServerObject();
			  ILayer editLayer = mapServer.getLayer("",layerId);
			  IFeatureLayer featureLayer = new IFeatureLayerProxy(editLayer);
			  IFeatureClass featureClass = featureLayer.getFeatureClass();
			  //IQueryFilter queryFilter = new QueryFilter();//不能使用这种方法
			  IQueryFilter queryFilter =(IQueryFilter)context.createObject(QueryFilter.getClsid());
			  String whereString="\"ACCEPTNO\" = '"+acceptNo+"'";
			  System.out.println(whereString);
			  queryFilter.setWhereClause(whereString);  
			  //queryFilter.setSubFields("ACCEPTNO") ;//设置了这个选项以后，将缺少shape
			  featureCursor = featureClass.IFeatureClass_update(queryFilter, false);
			  IFeature feature;
			  
			  if((feature = featureCursor.nextFeature()) != null)
			  {
				  System.out.println("已经找到acceptNo为"+acceptNo+"的案件,开始修改属性");
				  String[] fieldValues=fieldAndValue.split(";");
				  for(int i=0;i<fieldValues.length;i++)
				  {
					  String[] fieldvalueStrs=fieldValues[i].split(",");
					  if(fieldvalueStrs.length==2)
					  {
						  String fieldStr=fieldvalueStrs[0];
						  String valueStr=fieldvalueStrs[1];
						  feature.setValue(feature.getFields().findField(fieldStr), valueStr);
					  }
				  }
				  feature.store();
				  context.releaseContext();
				  return EditResult.Succeed;
			  }
			  else 
			  {
				  context.releaseContext();
				  System.out.println("找不到acceptNo为"+acceptNo+"的案件");
				  return EditResult.Failed;
			   }
      }
      catch(Exception ee)
      {
    	  ee.printStackTrace();
    	  if(context!=null)
    	  {
    		  
    	      context.releaseContext();
    	  }
    	  return EditResult.Failed;
      }
	}
	
	//保存线
	//由于现在的json解码方法里面没有array的方法，所以现在暂时用字符串的形式把点传输过来，后续工作者可以寻求更好的方法
	//字符串的格式：“x1,y1,x2,y2....”
	@SuppressWarnings({ "unused", "unchecked" })
	 public String  addPolyline(java.lang.String pointListString,String serverName,String serverType,Integer layerId,String acceptNo) throws AutomationException,IOException
	 {
		 String[] pointArr=pointListString.split(",");
	  IServerContext context = null;
      try
      {
    	      context =ServerContextFactory.getContext(serverName, serverType);
			  MapServer mapServer = (MapServer) context.getServerObject();
			  ILayer editLayer = mapServer.getLayer("",layerId);
			  System.out.println("编辑的图层名称:"+editLayer.getName());
			  IFeatureLayer featureLayer = new IFeatureLayerProxy(editLayer);
			  IFeatureClass featureClass = featureLayer.getFeatureClass();
			  IFeature feature = featureClass.createFeature();
			  IFields fields = feature.getFields(); 
			  Polyline p=(Polyline)context.createObject(Polyline.getClsid());
		      for  ( int  i =  0 ; i < pointArr.length; i+=2)    
		      {    
		            IPoint pPoint;     
		            pPoint = (IPoint)context.createObject(Point.getClsid());;    
		            pPoint.setX(Double.parseDouble(pointArr[i]));
		            pPoint.setY(Double.parseDouble(pointArr[i+1]));
		            p.addPoint(pPoint, null, null);   
		            System.out.println(pointArr[i]);
		            System.out.println(pointArr[i+1]);
		       }
			  feature.setShapeByRef( p);
			  feature.setValue(fields.findField("acceptNo"), acceptNo);
			  feature.store();  
			  context.releaseContext();
	    	  return EditResult.Succeed;
          }
          catch(Exception ee)
          {
        	  ee.printStackTrace();
        	  if(context!=null)
        	  {
        	    context.releaseContext();
        	  }
        	  return EditResult.Failed;
          }
	}
	
	//保存线
	//由于现在的json解码方法里面没有array的方法，所以现在暂时用字符串的形式把点传输过来，后续工作者可以寻求更好的方法
	//字符串的格式：“x1,y1,x2,y2....”
	@SuppressWarnings({ "unused", "unchecked" })
	 public String  addPolygon(java.lang.String pointListString,String serverName,String serverType,Integer layerId,String acceptNo) throws AutomationException,IOException
	 {
		 String[] pointArr=pointListString.split(",");
	     IServerContext context = null;
      try
      {
    	      context =ServerContextFactory.getContext(serverName, serverType);
			  MapServer mapServer = (MapServer) context.getServerObject();
			  ILayer editLayer = mapServer.getLayer("",layerId);
			  System.out.println("编辑的图层名称:"+editLayer.getName());
			  IFeatureLayer featureLayer = new IFeatureLayerProxy(editLayer);
			  IFeatureClass featureClass = featureLayer.getFeatureClass();
			  IFeature feature = featureClass.createFeature();
			  IFields fields = feature.getFields(); 
			  Polygon polygon=(Polygon)context.createObject(Polygon.getClsid());
		      for  ( int  i =  0 ; i < pointArr.length; i+=2)    
		      {    
		            IPoint pPoint;     
		            pPoint = (IPoint)context.createObject(Point.getClsid());;    
		            pPoint.setX(Double.parseDouble(pointArr[i]));
		            pPoint.setY(Double.parseDouble(pointArr[i+1]));
		            polygon.addPoint(pPoint, null, null);  
		       }
			  feature.setShapeByRef( polygon);
			  feature.setValue(fields.findField("acceptNo"), acceptNo);
			  feature.store();  
			  context.releaseContext();
	    	  return EditResult.Succeed;
          }
          catch(Exception ee)
          {
        	  ee.printStackTrace();
        	  if(context!=null)
        	  {
        	    context.releaseContext();
        	  }
        	  return EditResult.Failed;
          }
	}
	
	//删除要素
	@SuppressWarnings({ "unused", "unchecked" })
	 public String deleteFeature(String objectID,String serverName,String serverType,Integer layerId) throws AutomationException,IOException
	 {
		  IServerContext context = null;
		  IFeatureCursor featureCursor=null;
	      try
	      {
	    	     context =ServerContextFactory.getContext(serverName, serverType);
				  MapServer mapServer = (MapServer) context.getServerObject();
				  ILayer editLayer = mapServer.getLayer("",layerId);
				  IFeatureLayer featureLayer = new IFeatureLayerProxy(editLayer);
				  IFeatureClass featureClass = featureLayer.getFeatureClass();
				  //IQueryFilter queryFilter = new QueryFilter();//不能使用这种方法
				  IQueryFilter queryFilter =(IQueryFilter)context.createObject(QueryFilter.getClsid());
				  String whereString="\"OBJECTID\" = '"+objectID+"'";
				  System.out.println(whereString);
				  queryFilter.setWhereClause(whereString);  
				  //queryFilter.setSubFields("ACCEPTNO") ;//设置了这个选项以后，将缺少shape
				  featureCursor = featureClass.IFeatureClass_update(queryFilter, false);
				  IFeature feature;
				  
				  if((feature = featureCursor.nextFeature()) != null)
				  {
					  feature.delete();
					  context.releaseContext();
					  return EditResult.Succeed;
				  }
				  else 
				  {
					  context.releaseContext();
					  System.out.println("找不到objectID为"+objectID+"的案件");
					  return EditResult.Failed;
				   }
	      }
	      catch(Exception ee)
	      {
	    	  ee.printStackTrace();
	    	  if(context!=null)
	    	  {
	    		  
	    	      context.releaseContext();
	    	  }
	    	  return EditResult.Failed;
	      }
		}
	
	//删除点要素
	@SuppressWarnings({ "unused", "unchecked" })
	public String deletePtFeature(String objectID,String serverName,String serverType,Integer layerId) throws AutomationException,IOException
	 {
		  IServerContext context = null;
		  IFeatureCursor featureCursor=null;
	      try
	      {
	    	     context =ServerContextFactory.getContext(serverName, serverType);
				  MapServer mapServer = (MapServer) context.getServerObject();
				  ILayer editLayer = mapServer.getLayer("",layerId);
				  IFeatureLayer featureLayer = new IFeatureLayerProxy(editLayer);
				  IFeatureClass featureClass = featureLayer.getFeatureClass();
				  //IQueryFilter queryFilter = new QueryFilter();//不能使用这种方法
				  IQueryFilter queryFilter =(IQueryFilter)context.createObject(QueryFilter.getClsid());
				  //String whereString="\"OBJECTID\" = '"+objectID+"'";
				  String whereString="1=1";
				  System.out.println(whereString);
				  queryFilter.setWhereClause(whereString);  
				  //queryFilter.setSubFields("ACCEPTNO") ;//设置了这个选项以后，将缺少shape
				  featureCursor = featureClass.IFeatureClass_update(queryFilter, false);
				  IFeature feature;
				  
				  feature = featureCursor.nextFeature();
				  while(feature!=null)
				  {
					  feature.delete();
					  feature = featureCursor.nextFeature();
				  }
				  if(feature!= null)
				  {
					  
					 
				  }
				  else 
				  {
					  context.releaseContext();
					  System.out.println("找不到objectID为"+objectID+"的案件");
					  return EditResult.Failed;
				   }
				  context.releaseContext();
				  return EditResult.Succeed;
	      }
	      catch(Exception ee)
	      {
	    	  ee.printStackTrace();
	    	  if(context!=null)
	    	  {
	    		  
	    	      context.releaseContext();
	    	  }
	    	  return EditResult.Failed;
	      }
	 }
	
	//删除案件点
	@SuppressWarnings({ "unused", "unchecked" })
	public String deleteCaseFeature(String acceptNo,String serverName,String serverType,Integer layerId) throws AutomationException,IOException
	 {
		  IServerContext context = null;
		  IFeatureCursor featureCursor=null;
	      try
	      {
	    	     context =ServerContextFactory.getContext(serverName, serverType);
				  MapServer mapServer = (MapServer) context.getServerObject();
				  ILayer editLayer = mapServer.getLayer("",layerId);
				  IFeatureLayer featureLayer = new IFeatureLayerProxy(editLayer);
				  IFeatureClass featureClass = featureLayer.getFeatureClass();
				  //IQueryFilter queryFilter = new QueryFilter();//不能使用这种方法
				  IQueryFilter queryFilter =(IQueryFilter)context.createObject(QueryFilter.getClsid());
				  
				  String whereString="\"ACCEPTNO\" = '"+acceptNo+"'";
				  System.out.println(whereString);
				  queryFilter.setWhereClause(whereString);  
				  //queryFilter.setSubFields("ACCEPTNO") ;//设置了这个选项以后，将缺少shape
				  featureCursor = featureClass.IFeatureClass_update(queryFilter, false);
				  IFeature feature;
				  
				  feature = featureCursor.nextFeature();
				  while(feature!=null)
				  {
					  feature.delete();
					  feature = featureCursor.nextFeature();
				  }
				  if(feature!= null)
				  {
					  
					 
				  }
				  else 
				  {
					  context.releaseContext();
					  System.out.println("找不到acceptNo为"+acceptNo+"的案件");
					  return EditResult.Failed;
				   }
				  context.releaseContext();
				  return EditResult.Succeed;
	      }
	      catch(Exception ee)
	      {
	    	  ee.printStackTrace();
	    	  if(context!=null)
	    	  {
	    		  
	    	      context.releaseContext();
	    	  }
	    	  return EditResult.Failed;
	      }
	 }
}
